package com.gcy.wanandroid.http.httptool;

import android.util.Log;

import androidx.annotation.NonNull;

import com.gcy.wanandroid.config.Constants;
import com.gcy.wanandroid.util.NetworkUtils;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.HashSet;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author: gcy
 * @description: 在请求头中添加 Cookie 信息
 * @version: 1.0
 * @CreateTime: 2023-05-17  10:04
 */
public class AddCookiesInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        if (!NetworkUtils.isConnected()) {
            throw new HttpException("网络连接异常，请检查网络后重试");
        }

        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = Hawk.get(Constants.HawkCode.COOKIE);
        if (preferences != null) {
            for (String cookie : preferences) {
                builder.addHeader("Cookie", cookie);
                Log.v("OkHttp", "Adding Header" + cookie);
            }
        }
        return chain.proceed(builder.build());
    }
}
